package signature

import (
	"fmt"
	"sort"
	"strings"
	"strconv"
	"crypto/md5"
	"github.com/astaxie/beego"
)

// 生成sign
func MakeSign(params map[string]interface{}, key string) string {
	paramsNew := make(map[string]string)
	for k, v := range params {
		if s, ok := v.(string); ok {
			paramsNew[k] = s
		} else if _, ok := v.(int); ok {
			paramsNew[k] = strconv.Itoa(v.(int))
		} else if _, ok := v.(float64); ok {
			paramsNew[k] = strconv.FormatFloat(v.(float64), 'f', -1, 32)
		} else {
			beego.Debug("map格式错误,key,value:", k, v)
		}
	}
	var keys []string
	var sorted []string
	for k, v := range paramsNew {
		if k != "sign" && v != "" {
			keys = append(keys, k)
		}
	}
	sort.Strings(keys)
	for _, k := range keys {
		sorted = append(sorted, fmt.Sprintf("%s=%s", k, paramsNew[k]))
	}
	str := strings.Join(sorted, "&")
	str += "&key=" + key
	return fmt.Sprintf("%X", md5.Sum([]byte(str)))
}
